import useUserStore from '@/stores/user'
import axios from 'axios'
import { ElNotification } from 'element-plus'
import router from '@/router'

const http = axios.create({
    baseURL: '/api',
})

// 请求拦截器
http.interceptors.request.use(
    (config) => {
        const store = useUserStore()
        if (store.userInfo.tokenValue) {
            config.headers['token'] = store.userInfo.tokenValue
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    },
)

// 响应拦截器
http.interceptors.response.use(
    (response) => {
        if (response.data.code !== 1) {
            if (response.data.msg) {
                ElNotification.error({ title: '错误', message: response.data.msg })
            }
            if (response.data.code === 402) {
                const store = useUserStore()
                store.setUserInfo({})
                router.push('/login')
            }

            return Promise.reject(response.data)
        }
        return response.data
    },
    (error) => {
        return Promise.reject(error)
    },
)

export default http
